package com.mao.model;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.HibernateException;
import org.hibernate.usertype.UserType;

public class EnumStringUserType<E extends Enum<E>> implements UserType {

	private Class<E> clazz = null;

	private static final int[] sqlTypes = { Types.VARCHAR };

	protected EnumStringUserType(Class<E> c) {

		clazz = c;

	}

	public int[] sqlTypes() {

		return sqlTypes;

	}

	public Class returnedClass() {

		return clazz;

	}

	public boolean equals(Object x, Object y) throws HibernateException {

		if (x == y)

			return true;

		if (x == null || y == null)

			return false;

		else

			return x.equals(y);

	}

	public int hashCode(Object x) throws HibernateException {

		return x.hashCode();

	}

	public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
			throws HibernateException, SQLException {

		String value = rs.getString(names[0]);

		Object result = null;

		if (!rs.wasNull())

			result = Enum.valueOf(clazz, value);

		return result;

	}

	public void nullSafeSet(PreparedStatement st, Object value, int index)
			throws HibernateException, SQLException {

		if (null == value)

			st.setNull(index, Types.VARCHAR);

		else

			st.setString(index, ((Enum) value).name());

	}

	public Object deepCopy(Object value) throws HibernateException {

		return value;

	}

	public boolean isMutable() {

		return false;

	}

	public Serializable disassemble(Object value) throws HibernateException {

		return (Serializable) value;

	}

	public Object assemble(Serializable cached, Object owner)
			throws HibernateException {

		return cached;

	}

	public Object replace(Object original, Object targer, Object owner)
			throws HibernateException {

		return original;

	}

}
